package net.oschina.ivansong.rpc.base.imp.privider.test;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import net.oschina.ivansong.rpc.base.demo.api.IUserService;

public class Privider {
	private static Map<String, Class<?>> serviceMap = new HashMap<>();
	static {
		serviceMap.put(IUserService.class.getName(), UserService.class);
	}

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		try {
			ServerSocket socketServer = new ServerSocket(5666);
			while(true) {
			
				final Socket socket =socketServer.accept();
				Runnable run = new Runnable() {
					
					@Override
					public void run() {
						try {
							ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
							
							String className = in.readUTF();
							String methodName = in.readUTF();
							Class<?>[] parameterTypes = (Class<?>[]) in.readObject();
	                        Object[] objects = (Object[]) in.readObject();
							System.out.println("className:" + className + ", methodName:" + methodName);
							Class<?> cla = serviceMap.get(className);
							if (cla != null) {
								Method method = cla.getMethod(methodName, parameterTypes);
								if (method != null) {
									Object result = method.invoke(cla.newInstance(), objects);
									ObjectOutputStream outObj = new ObjectOutputStream(socket.getOutputStream());
									
									outObj.writeObject(result);
									outObj.close();
								}
							}
							in.close();
	                        socket.close();
	                    } catch (Exception e) {
	                        e.printStackTrace();
	                    }
					}
				};
				 new Thread(run).start();
				
			}
		} catch (IOException e) {
			
			e.printStackTrace();
		}

	}
}
